import { useEffect, useState } from "react";
import { Form, Input, Tabs, Button, Table, Switch } from "antd";
const { TabPane } = Tabs;

export default function FeeManagement() {
  const [form] = Form.useForm();
  const [activeTab, setActiveTab] = useState("enterprise"); // 当前选中的选项卡
  const [data, setData] = useState({
    enterprise: {
      openingFee: { USD: "100", USDC: "200", USDT: "300" },
      managementFee: { USD: "10", USDC: "20", USDT: "30" },
    },
    individual: {
      openingFee: { USD: "50", USDC: "100", USDT: "150" },
      managementFee: { USD: "5", USDC: "10", USDT: "15" },
    },
    initialData: {
      recharge: [
        {
          key: "1",
          type: "法币跨行转人",
          currency: "EUR",
          fee: "",
          switchOn: false,
        },
        {
          key: "2",
          type: "",
          currency: "CNH",
          fee: "",
          switchOn: false,
        },
        {
          key: "3",
          type: "",
          currency: "USD",
          fee: "",
          switchOn: false,
        },
        {
          key: "4",
          type: "法币同行转人",
          currency: "EUR",
          fee: "",
          switchOn: false,
        },
        {
          key: "5",
          type: "",
          currency: "CNH",
          fee: "",
          switchOn: false,
        },
        {
          key: "6",
          type: "",
          currency: "USD",
          fee: "",
          switchOn: false,
        },
        {
          key: "7",
          type: "",
          currency: "USDC",
          fee: "",
          switchOn: false,
        },
        {
          key: "8",
          type: "U币转入",
          currency: "USDT",
          fee: "",
          switchOn: false,
        },
      ],
      exchange: [
        {
          key: "4",
          type: "法币间兑换",
          buycurrency: "USD",
          shellcurrency: "EUR",
          fee: "",
          switchOn: false,
        },
        {
          key: "5",
          type: "",
          buycurrency: "CNH",
          shellcurrency: "EUR",
          fee: "",
          switchOn: false,
        },
        {
          key: "6",
          type: "",
          buycurrency: "EUR",
          shellcurrency: "USD",
          fee: "",
          switchOn: false,
        },
        {
          key: "7",
          type: "",
          buycurrency: "CNH",
          shellcurrency: "USD",
          fee: "",
          switchOn: false,
        },
        {
          key: "8",
          type: "",
          buycurrency: "USD",
          shellcurrency: "CNH",
          fee: "",
          switchOn: false,
        },
        {
          key: "9",
          type: "",
          buycurrency: "EUR",
          shellcurrency: "CNH",
          fee: "",
          switchOn: false,
        },
        {
          key: "10",
          type: "法币与U币兑换",
          buycurrency: "USDT",
          shellcurrency: "USD",
          fee: "",
          switchOn: false,
        },
        {
          key: "11",
          type: "",
          buycurrency: "USDT",
          shellcurrency: "EUR",
          fee: "",
          switchOn: false,
        },
        {
          key: "12",
          type: "",
          buycurrency: "USDC",
          shellcurrency: "USD",
          fee: "",
          switchOn: false,
        },
        {
          key: "13",
          type: "",
          buycurrency: "USDC",
          shellcurrency: "EUR",
          fee: "",
          switchOn: false,
        },
        {
          key: "14",
          type: "U币与法币兑换",
          buycurrency: "USD",
          shellcurrency: "USDT",
          fee: "",
          switchOn: false,
        },
        {
          key: "15",
          type: "",
          buycurrency: "EUR",
          shellcurrency: "USDT",
          fee: "",
          switchOn: false,
        },
        {
          key: "16",
          type: "",
          buycurrency: "USD",
          shellcurrency: "USDC",
          fee: "",
          switchOn: false,
        },
        {
          key: "17",
          type: "",
          buycurrency: "EUR",
          shellcurrency: "USDC",
          fee: "",
          switchOn: false,
        },
      ],
      transfer: [
        {
          key: "4",
          type: "法币转出",
          currency: "EUR",
          fee: "",
          min: "",
          switchOn: false,
        },
        {
          key: "5",
          type: "",
          currency: "USD",
          fee: "",
          min: "",
          switchOn: false,
        },
        {
          key: "10",
          type: "U币转出",
          currency: "USDC",
          fee: "",
          min: "",
          switchOn: false,
        },
        {
          key: "11",
          type: "",
          currency: "USDT",
          fee: "",
          min: "",
          switchOn: false,
        },
      ],
      settlement: [
        {
          key: "4",
          type: "结汇",
          currency: "CNH",
          fee: "",
          switchOn: false,
        },
      ],
    },
  });

  useEffect(() => {
    form.setFieldsValue(data[activeTab]);
  }, [activeTab, form, data]);

  const handleTabChange = (key: any) => {
    setActiveTab(key); // 切换选项卡
  };

  const handleFormSubmit = () => {
    form.validateFields().then((values) => {
      // 更新当前选项卡的数据
      setData((prevData) => ({
        ...prevData,
        [activeTab]: values,
      }));
      console.log("保存的数据：", values);
    });
  };
  const handleInputChange = (key: any, field: any, value: any, tab: any) => {
    const updatedData = { ...data.initialData };
    console.log("updatedData", updatedData);

    updatedData[tab] = updatedData[tab].map((item: any) =>
      item.key === key ? { ...item, [field]: value } : item
    );
  };
  const handleSwitchChange = (key: any, checked: any, tab: any) => {
    handleInputChange(key, "switchOn", checked, tab);
  };
  const rechargeColumns = [
    { title: "类型", dataIndex: "type", key: "type" },
    {
      title: "返点/分润",
      key: "switch",
      render: (_: any, record: any) => (
        <Switch
          checked={record.switchOn}
          onChange={(checked) =>
            handleSwitchChange(record.key, checked, "recharge")
          }
        />
      ),
    },
    { title: "币种", dataIndex: "currency", key: "currency" },
    {
      title: "费率",
      key: "fee",
      render: (_: any, record: any) => (
        <Input
          placeholder="请输入费率"
          value={record.fee}
          onChange={(e) =>
            handleInputChange(record.key, "fee", e.target.value, "recharge")
          }
        />
      ),
    },
  ];
  const exchangeColumns = [
    { title: "类型", dataIndex: "type", key: "type" },
    {
      title: "返点/分润",
      key: "switch",
      render: (_, record) => (
        <Switch
          checked={record.switchOn}
          onChange={(checked) =>
            handleSwitchChange(record.key, checked, "exchange")
          }
        />
      ),
    },
    { title: "卖出币种", dataIndex: "shellcurrency", key: "shellcurrency" },
    { title: "买入币种", dataIndex: "buycurrency", key: "buycurrency" },
    {
      title: "费率",
      key: "fee",
      render: (_, record) => (
        <Input
          placeholder="请输入"
          value={record.fee}
          onChange={(e) =>
            handleInputChange(record.key, "fee", e.target.value, "exchange")
          }
        />
      ),
    },
  ];
  const transferColumns = [
    { title: "类型", dataIndex: "type", key: "type" },
    {
      title: "返点/分润",
      key: "switch",
      render: (_, record) => (
        <Switch
          checked={record.switchOn}
          onChange={(checked) =>
            handleSwitchChange(record.key, checked, "transfer")
          }
        />
      ),
    },
    { title: "币种", dataIndex: "currency", key: "currency" },
    {
      title: "费率",
      key: "fee",
      render: (_, record) => (
        <Input
          placeholder="请输入费率"
          value={record.fee} // 正确绑定
          onChange={
            (e) =>
              handleInputChange(record.key, "fee", e.target.value, "transfer") // 正确更新 `fee`
          }
        />
      ),
    },
    {
      title: "最低",
      key: "min",
      render: (_, record) => (
        <Input
          placeholder="请输入费率"
          value={record.min} // 错误的绑定，应该是 `record.min`
          addonAfter="%"
          onChange={
            (e) =>
              handleInputChange(record.key, "min", e.target.value, "transfer") // 错误的字段，应该是 "min"
          }
        />
      ),
    },
  ];
  const settlementColumns = [
    { title: "类型", dataIndex: "type", key: "type" },
    {
      title: "返点",
      key: "switch",
      render: (_, record) => (
        <Switch
          checked={record.switchOn}
          onChange={(checked) =>
            handleSwitchChange(record.key, checked, "settlement")
          }
        />
      ),
    },
    { title: "币种", dataIndex: "currency", key: "currency" },
    {
      title: "费率",
      key: "fee",
      render: (_, record) => (
        <Input
          placeholder="请输入"
          value={record.fee}
          onChange={(e) =>
            handleInputChange(record.key, "fee", e.target.value, "settlement")
          }
        />
      ),
    },
  ];
  const renderFormItems = () => (
    <>
      <table className="table">
        <tbody>
          <tr>
            <td className="header">开户费</td>
            {["USD", "USDC", "USDT"].map((currency) => (
              <td key={`openingFee-${currency}`} className="header">
                <Form.Item
                  name={["openingFee", currency]}
                  style={{ marginBottom: 0 }}
                >
                  <Input placeholder="请输入" suffix={currency} />
                </Form.Item>
              </td>
            ))}
          </tr>
          <tr>
            <td className="header">账户管理费（月）</td>
            {["USD", "USDC", "USDT"].map((currency) => (
              <td key={`managementFee-${currency}`} className="header">
                <Form.Item
                  name={["managementFee", currency]}
                  style={{ marginBottom: 0 }}
                >
                  <Input placeholder="请输入" suffix={currency} />
                </Form.Item>
              </td>
            ))}
          </tr>
        </tbody>
      </table>
    </>
  );

  return (
    <div>
      <div
        style={{ fontSize: "16px", fontWeight: "bold", marginBottom: "16px" }}
      >
        开户费、管理费配置
      </div>
      <Tabs defaultActiveKey="enterprise" onChange={handleTabChange}>
        <TabPane tab="企业" key="enterprise">
          <Form form={form} initialValues={data.enterprise}>
            {renderFormItems()}
          </Form>
        </TabPane>
        <TabPane tab="个人" key="individual">
          <Form form={form} initialValues={data.individual}>
            {renderFormItems()}
          </Form>
        </TabPane>
      </Tabs>
      <div style={{ fontSize: "16px", fontWeight: "bold", marginTop: "20px" }}>
        客户交易费率
      </div>
      <Tabs
        defaultActiveKey="1"
        items={[
          {
            label: "充值",
            key: "1",
            children: (
              <Table
                columns={rechargeColumns}
                dataSource={data.initialData.recharge}
                pagination={false}
                style={{ width: "500px" }}
                bordered
                size="small"
              />
            ),
          },
          {
            label: "兑换",
            key: "2",
            children: (
              <Table
                columns={exchangeColumns}
                dataSource={data.initialData.exchange}
                pagination={false}
                style={{ width: "500px" }}
                bordered
                size="small"
              />
            ),
          },
          {
            label: "转账",
            key: "3",
            children: (
              <Table
                columns={transferColumns}
                dataSource={data.initialData.transfer}
                pagination={false}
                style={{ width: "500px" }}
                bordered
                size="small"
              />
            ),
          },
          {
            label: "结算",
            key: "4",
            children: (
              <Table
                columns={settlementColumns}
                dataSource={data.initialData.settlement}
                pagination={false}
                style={{ width: "500px" }}
                bordered
                size="small"
              />
            ),
          },
        ]}
      />
      <div style={{ textAlign: "center", marginTop: "16px" }}>
        <Button type="primary" onClick={handleFormSubmit}>
          保存
        </Button>
      </div>
    </div>
  );
}
